//
//  GHAddreeeMangeController.m
//  GodHorses
//
//  Created by Mac on 2017/11/15.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "GHAddreeeMangeController.h"
#import "GHAddressTableViewCell.h"
#import "GHAddAreaViewController.h"
#import "GHAddressModel.h"
@interface GHAddreeeMangeController ()
@property(nonatomic, strong) GHNoResultView                     *noresultView;
@property(nonatomic, strong) STButton                           *addButton;
@property(nonatomic, strong) NSMutableArray<GHAddressModel*>                     *dataSouce;
@end

@implementation GHAddreeeMangeController
#pragma mark --vc 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataSouce = [NSMutableArray new];
    self.title = @"收货地址管理";
    self.tableView.backgroundColor = GH_backgroundColor;
    [self configSubView];
   
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
     [self sendMyaddressRequest];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark --subView
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    self.noresultView = [[GHNoResultView alloc] initWithFrame:CGRectMake(0, 180, UIScreenWidth, 300)
                                                        title:@"抱歉,暂无收货地址"
                                                  buttonTitle:@"添加收货地址"
                                                 buttonHandle:^(NSString *titleString) {
                                                     [weakSelf onSelectedaddButton];
                                                 }];
    [self.tableView addSubview:self.noresultView];
    
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    footer.backgroundColor = self.tableView.backgroundColor;
    self.addButton = [[STButton alloc] initWithFrame:CGRectMake(30, 0, UIScreenWidth - 60, 44)
                                                        title:@"新增收货地址"
                                                   titleColor:GH_YellowBackGroundColor
                                                    titleFont:18
                      
                                                 cornerRadius:5
                                              backgroundColor:GH_BlackBackGroundColor
                                              backgroundImage:nil
                                                        image:nil];
    [self.addButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedaddButton];
    }];
    self.addButton.st_centerY = 50;
    self.addButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    self.addButton.hidden = YES;
    [footer addSubview:self.addButton];
    self.tableView.tableFooterView = footer;
    
    //mjrefresh

    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self sendMyaddressRequest];
    }];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSouce.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 120;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 10;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    GHAddressTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[GHAddressTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    cell.model = self.dataSouce[indexPath.section];
    __weak typeof(self) weakSelf =  self;
    [cell.defultButton setClicAction:^(UIButton *sender) {
        [weakSelf sendChangeDefultAddressRequestWithIndexPath:indexPath];
    }];
    [cell.editButton setClicAction:^(UIButton *sender) {
        [weakSelf editAddressWithIndexPath:indexPath];
    }];
    [cell.delButton setClicAction:^(UIButton *sender) {
        [weakSelf delAddressWithIndexPath:indexPath];
    }];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
#pragma mark --Private Method
- (void)updateDefultAddressWithIndexPath:(NSIndexPath*)indexPath{
    //置空所有选择
    GHAddressModel * model = self.dataSouce[indexPath.section];
    for (GHAddressModel * exitModel in self.dataSouce) {
        exitModel.is_default = @"0";
    }
    model.is_default = @"1";
    [self reloadData];
}
- (void)editAddressWithIndexPath:(NSIndexPath*)indexPath{
    GHAddressModel * model = self.dataSouce[indexPath.section];
    GHAddAreaViewController * vc = [GHAddAreaViewController new];
    vc.addressModel = model;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)delAddressWithIndexPath:(NSIndexPath*)indexPath{
    [self showAlertCancelAndConfirm:@"您确定要删除这条地址吗？" andWithBlock:^(NSString *name) {
        if ([name isEqualToString:@"确认"]) {
            [self sendDelAddressRequestWithIndexPath:indexPath];
        }
    }];
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
- (void)onSelectedaddButton{
    [self.navigationController pushViewController:[GHAddAreaViewController new] animated:YES];
}
#pragma mark --Private Method
- (void)reloadData{
    self.addButton.hidden = !self.dataSouce.count;
    self.noresultView.hidden = self.dataSouce.count;
    [self.tableView reloadData];
}
#pragma mark --NetWork Method
- (void)sendMyaddressRequest{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:@"http://test.smqyp.com/Api/system/get_receive_addr"
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 NSArray * arry = [responseObject valueForKey:@"data"];
                                                 self.dataSouce = [NSMutableArray new];
                                                 for (NSDictionary * addressDic in arry) {
                                                     GHAddressModel * model = [GHAddressModel mj_objectWithKeyValues:addressDic];
                                                     [self.dataSouce addObject:model];
                                                 }
                                                 [self reloadData];
                                                 [self.tableView.mj_header endRefreshing];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                // [SVProgressHUD showErrorWithStatus:error.desc];
                                                 self.dataSouce = [NSMutableArray new];
                                                 [self reloadData];
                                                 [self.tableView.mj_header endRefreshing];
                                             }];
}
- (void)sendChangeDefultAddressRequestWithIndexPath:(NSIndexPath*)indexPath{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    
    GHAddressModel * model = self.dataSouce[indexPath.section];
    if (model.addressId.length) {
         [dic setObject:model.addressId forKey:@"addr_id"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:@"http://test.smqyp.com/Api/system/set_default_addr"
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"更改成功"];
                                                 [self updateDefultAddressWithIndexPath:indexPath];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
    
    

}
- (void)sendDelAddressRequestWithIndexPath:(NSIndexPath*)indexPath{
    [SVProgressHUD showWithStatus:@"正在删除"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([GHUserManger defult].userID.length) {
        [dic setObject:[GHUserManger defult].userID forKey:@"uid"];
    }
    if ([GHUserManger defult].token.length) {
        [dic setObject:[GHUserManger defult].token forKey:@"token"];
    }
    
    GHAddressModel * model = self.dataSouce[indexPath.section];
    if (model.addressId.length) {
        [dic setObject:model.addressId forKey:@"addr_id"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:@"http://test.smqyp.com/Api/system/del_receive_addr"
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                                                 [self.dataSouce removeObject:model];
                                                 [self reloadData];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end
